package com.wwj.springboot.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wwj.springboot.entity.CmfzAdmin;
import com.wwj.springboot.mapper.CmfzAdminMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义认证Realm
 */
public class AuthenRealm extends AuthenticatingRealm{
    @Autowired
    private CmfzAdminMapper cmfzAdminDao;

    /**
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        /**
         * 1.从令牌中获取账号
         */
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = String.valueOf(usernamePasswordToken.getPassword());

        /**
         * 2.通过数据库查询
         */
        CmfzAdmin admin = cmfzAdminDao.selectOne(
                new QueryWrapper<CmfzAdmin>()
                        .eq("username", username)
        );


        /**
         * 3.查询数据不为null 封装info返回
         */
        if (admin != null) {

            /**
             * 参数1 账号
             * 参数2 密码
             * 参数3 盐值
             * 参数4 当前Realm对象的名字
             *
             *
             */
//            处理数据库查询到盐值
            ByteSource saltSource = ByteSource.Util.bytes(admin.getSalt());

            return new SimpleAuthenticationInfo(
                    admin.getUsername(),
                    admin.getPassword(),
                    saltSource,
                    this.getName()
            );
        }

        return null;
    }
}
